﻿using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using TMM.Common;

namespace TMM
{
	[Register ("AppDelegate")]
	public partial class AppDelegate : UIApplicationDelegate
	{
		UIWindow window;
		TMMViewController viewController;

		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			window = new UIWindow (UIScreen.MainScreen.Bounds);
			viewController = new TMMViewController ();
			var navController = new UINavigationController (viewController);
			navController.SetNavigationBarHidden (true, false);

			window.RootViewController = navController;
			window.MakeKeyAndVisible ();
			
			return true;
		}

		public override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken)
		{
			string trimmedDeviceToken = deviceToken.Description;
			if (!string.IsNullOrWhiteSpace(trimmedDeviceToken))
			{
				trimmedDeviceToken = trimmedDeviceToken.Trim('<');
				trimmedDeviceToken = trimmedDeviceToken.Trim('>');
			}

			DeviceInfo.Id = trimmedDeviceToken;
			viewController.LoadApplication (null);
		}

		public override void FailedToRegisterForRemoteNotifications (UIApplication application , NSError error)
		{
            viewController.LoadApplication(null);
		}

		public override void ReceivedRemoteNotification (UIApplication application, NSDictionary userInfo)
		{
			HandleRemoteNotification (application, userInfo);
		}

		public override void DidReceiveRemoteNotification (UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
		{
			HandleRemoteNotification (application, userInfo);
		}

		private void HandleRemoteNotification(UIApplication application, NSDictionary userInfo){
			int ccdId = 0;
			int.TryParse(userInfo.ValueForKey (new NSString("data")).ToString(), out ccdId);

			int badgeNo = 0;
			int.TryParse(userInfo.ValueForKey (new NSString("aps")).ValueForKey (new NSString("badge")).ToString(), out badgeNo);
			application.ApplicationIconBadgeNumber = badgeNo;

			viewController.RefreshNotificationsCount ();
			viewController.UpdateUnreadNotification (ccdId);
		}
			
		public override void WillEnterForeground(UIApplication application)
		{
			viewController.RefreshNotificationsCount ();
		}
	}
}